<template>
  <transition name="slide-down">
    <div v-if="visible" class="fixed inset-0 bg-black bg-opacity-50 flex items-start justify-center pt-24 z-50">
      <div class="bg-white rounded-lg shadow-lg p-6 w-96 max-w-full mx-4">
        <div class="flex justify-between items-center mb-4">
          <h3 class="text-xl font-semibold text-gray-800">消息搜索</h3>
          <button
            @click="handleClose"
            class="text-gray-500 hover:text-gray-800 transition"
            aria-label="关闭搜索"
          ><span class="text-lg">✖️</span></button>
        </div>
        <input
          v-model.trim="keyword"
          @keyup.enter="emitSearch"
          placeholder="输入关键词"
          class="w-full border border-gray-300 rounded-lg px-4 py-2 focus:outline-none focus:ring-2 focus:ring-blue-200 transition mb-4"
        />
        <div class="flex space-x-6">
          <label class="inline-flex items-center space-x-2">
            <input type="checkbox" v-model="filters.text" class="form-checkbox text-blue-500 transition" />
            <span>文本</span>
          </label>
          <label class="inline-flex items-center space-x-2">
            <input type="checkbox" v-model="filters.emoji" class="form-checkbox text-green-500 transition" />
            <span>表情</span>
          </label>
          <label class="inline-flex items-center space-x-2">
            <input type="checkbox" v-model="filters.file" class="form-checkbox text-purple-500 transition" />
            <span>文件</span>
          </label>
        </div>
      </div>
    </div>
  </transition>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'

defineProps<{ visible: boolean }>()
const emit = defineEmits<{
  (e: 'search', payload: { keyword: string; types: string[] }): void
  (e: 'close'): void
}>()

const keyword = ref('')
const filters = ref({ text: true, emoji: true, file: true })

function emitSearch() {
  const types = Object.entries(filters.value)
    .filter(([, checked]) => checked)
    .map(([type]) => type)
  emit('search', { keyword: keyword.value, types })
}

function handleClose() {
  // ✅ 重置搜索条件
  keyword.value = ''
  filters.value = { text: true, emoji: true, file: true }

  // ✅ 发送清空后的搜索（等同于显示全部）
  emitSearch()

  // ✅ 通知父组件关闭
  emit('close')
}

// 实时监听关键词和筛选项变化
watch([keyword, filters], emitSearch, { immediate: true })
</script>

<style scoped>
.slide-down-enter-active, .slide-down-leave-active {
  transition: all 0.3s ease;
}
.slide-down-enter-from {
  opacity: 0;
  transform: translateY(-10px);
}
.slide-down-enter-to {
  opacity: 1;
  transform: translateY(0);
}
.slide-down-leave-from {
  opacity: 1;
  transform: translateY(0);
}
.slide-down-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}
</style>
